//
//  MineMessageViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON


enum MineMessageType: NSInteger {
    case comment = 0
    case zan
    case system
}
class MineMessageViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner, BottomShadow {
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var cornerSelectionView: CornerSelectionView!
    @IBOutlet weak var mainTableView: UITableView!
    var mineMessageType: MineMessageType = .comment
    
    var expandedIndexpaths:[IndexPath] = []
    var dataCommend:[myCommendModel] = []
    var dataLike:[myLikeModel] = []
    var dataMessage:[systemMessageModel] = []
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 1
    var totalPage:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()

    }
    
    func setUI() {
        titleLabel(text: "消息", nil)
        mainTableView.estimatedRowHeight = 100;
//        mainTableView.rowHeight = UITableViewAutomaticDimension;
        mainTableView.register(UINib(nibName: "\(MineMessageTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        cornerSelectionView.show(titles: ["评论", "赞", "系统消息"]) {[unowned self] (index) in
            var corner: UIRectCorner!
            switch index {
            case 0:
                corner = .topRight
                self.fetchMyComment(parameters:["page":self.page,"pageSize":10])
            case 2:
                corner = .topLeft
                self.fetchMySystem(parameters:["page":self.page,"pageSize":10])
            default:
                corner = [.topRight, .topLeft]
                self.fetchMyLike(parameters:["page":self.page,"pageSize":10])
            }
            
            let maskPath = UIBezierPath(roundedRect: self.mainView.bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
            let layer = self.mainView.layer.mask as? CAShapeLayer
            layer!.path = maskPath.cgPath
            self.mineMessageType = MineMessageType(rawValue: index)!
            self.mainTableView.reloadData()
        }
        addCornerWithView(aView: mainView, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTableView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        self.headerRefresh()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        page = 0
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        page += 1
        switch self.mineMessageType {
        case .comment:
            self.fetchMyComment(parameters: ["page":page,"pageSize":10])
        case .zan:
            self.fetchMyLike(parameters: ["page":page,"pageSize":10])
        case .system:
            self.fetchMySystem(parameters: ["page":page,"pageSize":10])
        }
        
    }
    
    override func setNavigation() {
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch self.mineMessageType {
        case .comment:
            let model = self.dataCommend
            return model.count
        case .zan:
            let model = self.dataLike
            return model.count
        case .system:
            let model = self.dataMessage
            return model.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MineMessageTableViewCell
        switch self.mineMessageType {
        case .comment:
            let model = self.dataCommend[indexPath.row]
            cell?.showDataWithComment(model: model)
        case .zan:
            let model = self.dataLike[indexPath.row]
            cell?.showDataWithLike(model: model)
        case .system:
            let model = self.dataMessage[indexPath.row]
            cell?.showDataWithSystem(model: model)
            if  expandedIndexpaths.contains(indexPath) {
                cell?.expanded  = true
            }else {
                cell?.expanded  = false
            }
            cell?.expandClosure = {() -> Void in
                if !(cell?.expanded!)! {
                    self.expandedIndexpaths.append(indexPath)
                }else{
                    let index = self.expandedIndexpaths.index(of: indexPath)
                    self.expandedIndexpaths.remove(at: index!)
                }
                tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.mineMessageType == .comment {
            let model = self.dataCommend[indexPath.row]
            let comm = CommentController()
            comm.model = model
            self.navigationController?.pushViewController(comm, animated: true)
        }
    }
    /// 获取我的评论
    func fetchMyComment(parameters: [String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(myCommenteUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary!
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = data["rows"]?.array!
                                        if self.page == 1{
                                            self.dataCommend.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr! {
                                            let dic = subject.dictionary!
                                            var model = myCommendModel(fromDic: dic)
                                            
                                            let label = dic["beRepliedUser"]
                                            if !(label?.isEmpty)!{
                                                model.initReplied(dic: (label?.dictionary!)!)
                                            }
                                            let comm = dic["commentUser"]
                                            if !(comm?.isEmpty)!{
                                                model.initAuthor(dic: (comm?.dictionary!)!)
                                            }
                                            
                                            let channel = dic["info"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.dataCommend.append(model)
                                            
                                        }
                                        if self.totalPage == self.dataCommend.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                
                                    } else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                       self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.dataCommend.removeAll()
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                            }
                            
        }
        
    }
    
    /// 获取banner数据
    func fetchMyLike(parameters: [String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(myLikeUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary!
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = data["rows"]?.array!
                                        if self.page == 1{
                                            self.dataLike.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr! {
                                            let dic = subject.dictionary!
                                            var model = myLikeModel(fromDic: dic)
                                            
                                            let comm = dic["liker"]
                                            if !(comm?.isEmpty)!{
                                                model.initAuthor(dic: (comm?.dictionary!)!)
                                            }
                                            
                                            let comment = dic["info"]
                                            if !(comment?.isEmpty)!{
                                                model.initCommentModel(dic: (comment?.dictionary!)!)
                                            }
                                            self.dataLike.append(model)
                                        }
                                        if self.totalPage == self.dataLike.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.dataLike.removeAll()
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                            }
                            
        }
        
    }
    
    /// 获取banner数据
    func fetchMySystem(parameters: [String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(myMessageUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary!
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = data["rows"]?.array!
                                        if self.page == 1{
                                            self.dataMessage.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr! {
                                            let dic = subject.dictionary!
                                            var model = systemMessageModel(fromDic: dic)
                                            let label = dic["miUser"]
                                            if !(label?.isEmpty)!{
                                                model.initGrade(dic: (label?.dictionary!)!)
                                            }
                                            self.dataMessage.append(model)
                                        }
                                        if self.totalPage == self.dataMessage.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.dataMessage.removeAll()
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                            }
                            
        }
        
    }
}
